/*
 * Copyright (C) 2008-2011 University of Deusto
 * 
 * All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.
 * 
 * This software consists of contributions made by many individuals, 
 * listed below:
 *
 * Author: Aitor Gómez Goiri <aitor.gomez@deusto.es>
 */
package otso.se.network.sockets.communication.abstraction.client;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.restlet.resource.ResourceException;

import otso.se.network.sockets.communication.abstraction.HttpRequest.Operation;
import otso.se.network.sockets.communication.abstraction.HttpResponse;
import otso.se.network.sockets.communication.abstraction.tcp.HttpSocketRequest;

public class ClientResource {
	final String url;
	final long timeout;
	ExecutorService ex;
	
	protected ClientResource(String originalURL, long timeout) {
		this.url = originalURL;
		this.timeout = timeout;
	}
	
	protected void useExecutor(ExecutorService executor) {
		this.ex = executor;
	}
	
	public HttpResponse get(/*Mediatype*/) throws InterruptedException, ExecutionException, TimeoutException {
		return makeRequest(Operation.GET);
	}
	
	public HttpResponse post(/*Mediatype*/) throws InterruptedException, ExecutionException, TimeoutException {
		return makeRequest(Operation.POST);
	}
	
	public HttpResponse delete(/*Mediatype*/) throws InterruptedException, ExecutionException, TimeoutException {
		return makeRequest(Operation.DELETE);
	}
	
	public HttpResponse put(/*Mediatype*/) throws InterruptedException, ExecutionException, TimeoutException {
		return makeRequest(Operation.PUT);
	}
	
	private HttpResponse makeRequest(Operation op) throws InterruptedException, ExecutionException, TimeoutException {
		final HttpSocketRequest socketClient = new HttpSocketRequest(this.url,op);
		
		final Future<HttpResponse> future = this.ex.submit(socketClient);
		try {
			return future.get();//timeout, TimeUnit.MILLISECONDS);
		} catch(ExecutionException e) {
			if(e.getCause() instanceof ResourceException) {
				throw (ResourceException)e.getCause();
			}
			throw e;
		}
	}
}